# -*- coding: UTF-8 -*-

import datetime
import sys
from sqlalchemy import and_, func, or_
from typing import Dict, List, Any, Generator

from sqlalchemy import Boolean, Column, DateTime, Integer, String, Index, Table, ForeignKey, text, JSON, TEXT, distinct
from sqlalchemy.orm import Session, relationship

from app.manage_notice.models.manage_notice_team import ManageNoticeTeam
from common.database import Base
from common.database import SessionMixin
from common.utils import is_empty
from core.logger import logger

__all__ = ['ManageNoticeDepartment']


class ManageNoticeDepartment(Base, SessionMixin):
    '''
    主机部门
    '''
    __tablename__ = "manage_notice_department"
    name = Column(String(64), nullable=False, comment='部门名称')
    notice_teams_uuid = Column(JSON, nullable=False, default=[], comment='通知小组')
    comment = Column(String(256), nullable=True, comment='部门说明')

    __table_args__ = (
        Index('idx_manage_notice_department_name', 'name', unique=True),
        {
            'mysql_engine': 'innodb',
            'mysql_charset': 'utf8mb4',
            'mysql_collate': 'utf8mb4_unicode_ci',
            'extend_existing': True,
            'mysql_row_format': 'dynamic'
        }
    )

    def __repr__(self):
        return f"<manage_notice_department='{self.name}'>"



    def object_to_dict(self, db: Session):
        result = {
            key: getattr(self, key)
            for key in self.__mapper__.c.keys()
        }
        # 方便前端直接展示名称
        result["notice_teams_name"] = []
        if result["notice_teams_uuid"]:
            for notice_team_uuid in result["notice_teams_uuid"]:
                notice_team_info = ManageNoticeTeam.get_object_info_by_uuid(db, notice_team_uuid)
                result["notice_teams_name"].append(notice_team_info["name"])
        return result



    @classmethod
    def get_object_info_by_notice_team(cls, db: Session, notice_team_uuid: str):
        object_info = db.query(cls).filter(
            func.json_contains(cls.notice_teams_uuid, str(notice_team_uuid)) == 1
        ).to_dict()

        return object_info
